from flask import render_template,redirect,url_for
from flask_login import login_required, logout_user, current_user


from lib.form import Form
from model.user import UserDao

from core import login_manager
from service.user import UserForm, LoginForm, UserService

from flask import jsonify
from bson.objectid import ObjectId

from controller import app

import json

@login_manager.user_loader
def load_user(_id):
    """This is a callback for the LoginManager class, it is used to reload the user object from the user ID stored in the session. 
    Arguments 
        _id -- The unicode string type, ID of a user
    Return 
        -- The user object if ID is valid, otherwise return None
    """
    user_dao = UserDao()
    return user_dao.find_one({'_id':ObjectId(_id)})


@app.route('/validate_signup')
@app.route('/validate_signup', methods=['GET','POST'])
def validate_signup():
    """ Ajax validation for multiple submit pages
    """
    form = UserForm()
    return jsonify(errors=form.errors)

@app.route("/signup", methods=["GET","POST"])
def signup():
    form = UserForm()
    service = UserService()
    if form.is_submitted():
        if service.signup(form):
            return render_template('login.html')
        else:
            return render_template('signup.html', errors_json=json.dumps(form.errors))
    else:
        return render_template('signup.html', errors_json=[])

@app.route("/login")                 
@app.route("/login", methods=["GET", "POST"])
def login():
    '''When a user logs in, their session is marked as 'fresh'.
    '''
    form = LoginForm()
    if form.is_submitted():
        if form.errors == []:
            service = UserService()
            ret = service.login(form.account, form.password, form.remember_me)
            #flash('Logged in successfully!')
            #return render_template('products.html', mytest = 'You logged in')
            #return render_template('setting.html')
            if ret:
                return render_template('index.html', username=current_user.username)
            #return redirect(request.args.get("next") or url_for("index"))
            else:
                return render_template("login.html", errors_json=[])
        else: # If input has error
            return render_template("login.html", errors_json=json.dumps(form.errors))
    else:
        return render_template("login.html", errors_json=[])


@app.route('/user_portal')
@app.route('/user_portal', methods=['GET','POST'])
@login_required
def user_portal():
    return render_template('user_portal.html', tickets=None)

@app.route("/user_manager")
@login_required
def user_manager():
    user_dao = UserDao()
    return render_template("users.html",users=list(user_dao.find()))

class UsersForm(Form):
    def __init__(self):
        '''Only accept POST request
        '''
        Form.__init__(self)

@app.route("/delete_users", methods=["GET", "POST"])
@login_required
def delete_users():
    user_dao = UserDao()
    form = UsersForm()
    ids = form.request.values.getlist('select-user')
    if ids is not None:
        for _id in ids:
            user = user_dao.find_one({'_id':ObjectId(_id)})
            user_dao.remove(user)
    return render_template("users.html",users=user_dao.find(), ids=ids)

@app.route("/logout")
@login_required
def logout():
    print 'logout called'
    logout_user()
    
    return redirect('login')
